/*
https://leetcode-cn.com/problems/perfect-squares/solution/wan-quan-ping-fang-shu-by-leetcode-solut-t99c/
 */
public class Solution279 {
    public int numSquares(int n) {
        int t=(int)Math.sqrt(n);
        if (t*t==n){
            return 1;
        }
        for (int i=1;i*i<n;i++){
            int p=n-i*i;
            int q=(int)Math.sqrt(p);
            if (q*q==p){
                return 2;
            }
        }
        while (n%4==0){
            n=n/4;
        }
        if (n%8==7){
            return 4;
        }
        return 3;
    }

    public static void main(String[] args) {
        System.out.println(new Solution279().numSquares(12));
    }
}
